package arithmetic;

import java.util.Scanner;
import java.util.Stack;

/**
 * 基于Dijkstra(迪克斯特拉算法) 的双栈求算数表达式的算法
 */
public class DijkstraEvaluateDemo {

    public static void main(String[] args) {
        //符号栈
        Stack<String> ops = new Stack<String>();
        //操作数栈
        Stack<Double> vals = new Stack<Double>();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String next = scanner.next();
            if (next.equals("("))  continue;
            else if (next.equals("+")) {
                ops.add("+");
            } else if (next.equals("-")) {
                ops.add("-");
            } else if (next.equals("*")) {
                ops.add("*");
            } else if (next.equals("/")) {
                ops.add("/");
            } else if (next.equals("sqrt")) {
                ops.add("sqrt");
            } else if (next.equals(")")) {
                String opsValue = ops.pop();
                Double data1 = vals.pop();
                if (opsValue.equals("+")) {
                    data1 = vals.pop() + data1;
                }
                if (opsValue.equals("-")) {
                    data1 = vals.pop() - data1;
                }
                if (opsValue.equals("*")) {
                    data1 = vals.pop() * data1;
                }
                if (opsValue.equals("/")) {
                    data1 = vals.pop() / data1;
                }
                vals.push(data1);
            } else {
                vals.push(Double.parseDouble(next));
            }

        }
        System.out.println(vals.pop());
    }
}
